import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {Http} from "@angular/http";
import {ActivatedRoute, ParamMap, Router} from "@angular/router";
import {MaintenanceService} from "../../shared/service/maintenance.service";
import {Maintenance} from "../../shared/model/maintenance";


@Component({
  selector: 'app-maintenance-edit-form',
  templateUrl: './maintenance-edit-form.component.html',
  styleUrls: ['./maintenance-edit-form.component.css']
})
export class MaintenanceEditFormComponent implements OnInit {
  typeForm: FormGroup;
  oid: string;
  type:Maintenance;

  constructor(private fb: FormBuilder,
              private routeInfo: ActivatedRoute,
              private maintenanceService:MaintenanceService,
              private router:Router) {
    this.createForm();
  }

  ngOnInit() {
    this.routeInfo.paramMap
      .switchMap((params: ParamMap) => this.maintenanceService.getMaintenanceTypeByOid(this.routeInfo.snapshot.params["oidByType"]))
      .subscribe(type => {
        this.type = type;
        this.typeForm.reset({
          oid:this.type.oid,
          id:this.type.id,
          name:this.type.name,
          description:this.type.description
        });
      });
  }

  onSubmit(val:any){
    let msg ="";
    if(!this.typeForm.get("id").value.replace(/^\s+|\s+$/g,"")){
      msg +=("请输入类型代号\n");
    }
    if(!this.typeForm.get("name").value.replace(/^\s+|\s+$/g,"")){
      msg +=("请输入类型名称\n");
    }

    if(msg){
      alert(msg);
    }else{
      this.maintenanceService.updateMaintenanceType(this.typeForm.value).then(res => {
        //状态码1为成功
        if (res.code === 1) {
          alert(res.message);
          this.maintenanceService.listFreshEvent.emit("edit");
          this.router.navigateByUrl('maintenance/new');
        } else {
          alert(res.message);
        }
      })
    }
  }

  toSearchId(){

  }

  createForm(){
    this.typeForm =this.fb.group({
      oid:'',
      id:new FormControl({value: '', disabled: true}),
      name: "",
      description: ""
    });
  }

}
